function bind(eventStr, callback) {
  if (this.addEventListener) {
    this.addEventListener(eventStr, callback, false)
  } else {
    this.attachEvent('on' + eventStr, callback)
  }
}

function getChildImgs(el) {
  if (el.tagName === 'img') return [el]
  const imgs = el.getElementsByTagName('img')
  if (Array.from) return Array.from(imgs)
  const resList = []
  for (let i = 0; i < imgs.length; i++) resList.push(imgs[i])
  return resList
}

function getParentPositionElement(el, oriEl = el) {
  if (!el) return oriEl
  const elStyle = getComputedStyle(el)
  if (['relative', 'absolute', 'fixed'].includes(elStyle.position)) {
    return el
  } else {
    return getParentPositionElement(el.parentElement, oriEl)
  }
}

export default {
  inserted(el) {
    const positionEl = getParentPositionElement(el)
    const positionStyle = getComputedStyle(positionEl)
    if (!['relative', 'absolute', 'fixed'].includes(positionStyle.position)) {
      positionEl.style.position = 'relative'
    }
    const childImgs = getChildImgs(el)
    childImgs.forEach($img => {
      $img.onmousedown = function (e) {
        e.preventDefault()
      }
    })
    const positionInfo = {
      oriZIndex: positionStyle.zIndex,
      oriTop: parseFloat(positionStyle.top),
      oriLeft: parseFloat(positionStyle.left),
      downX: null,
      downY: null,
      moveFlag: false,
    }
    bind.call(positionEl, 'mousedown', function (event) {
      positionEl.style.zIndex = 9999
      positionInfo.downX = event.x
      positionInfo.downY = event.y
      positionInfo.moveFlag = true
    })
    bind.call(positionEl, 'mousemove', function (event) {
      if (!positionInfo.moveFlag) return
      const offsetX = event.x - positionInfo.downX
      const offsetY = event.y - positionInfo.downY
      positionEl.style.top = positionInfo.oriTop + offsetY + 'px'
      positionEl.style.left = positionInfo.oriLeft + offsetX + 'px'
    })
    bind.call(positionEl, 'mouseup', function () {
      positionEl.style.zIndex = positionInfo.oriZIndex
      positionInfo.oriTop = parseFloat(positionStyle.top)
      positionInfo.oriLeft = parseFloat(positionStyle.left)
      positionInfo.moveFlag = false
    })
  },
}
